package org.nicocube.airain.domain.client.data;

import java.io.Serializable;

import org.nicocube.airain.domain.client.utils.DomainException;
import org.nicocube.airain.domain.client.utils.SequenceHolder;
import org.nicocube.airain.domain.server.utils.SequenceHolderImpl;

import com.db4o.config.annotations.Indexed;

/**
 * Common class for ordered stored Domain Object
 * 
 * @author nico
 * @version 0.1 
 */
public abstract class OrderedStorable implements Storable,Serializable{
	private static final long serialVersionUID = 1L;

	@Indexed
	private Long order = null;

	/**
	 * Tell if the object as been stored once 
	 * @return true if the order is set
	 */
	public boolean isSaved() {
		return order != null;
	}
	/**
	 * Retrieve the order of creation of the object
	 * @return the order 
	 */
	public Long getOrder() {
		return order;
	}

	/**
	 * Is used to set the order from a proper {@link SequenceHolderImpl}. As the order can be set only once, throw a DomainException if needed. 
	 * @param sequenceHolder the sequenceHolder to get the order from
	 * @throws DomainException the exception is thrown if isSaved() is true
	 */
	public void setOrder(SequenceHolder sequenceHolder) throws DomainException {
		if (isSaved()) throw new DomainException("Trying to modify an already set saveOrder.");
		try {
			this.order = sequenceHolder.nextVal();
		} catch (StorageException e) {
			 throw new DomainException("Error while getting retrieving next order value.",e);
		}
	}

	@Override
	public String toString() {
		return "order="+getOrder();
	}

}
